package com.gwtapps.serialization.client;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;



public class JSONDocument implements DocumentAdapter {

	protected class JSONDocumentObject implements DocumentObject{
		private JSONObject object = null;
		private String name;
		public JSONDocumentObject( String name, JSONObject object) {
			this.name = name;
			this.object = object;
		}		
		
		public JSONDocumentObject() {
		}
		
		public void setAttribute( String name, String value ) {	
			if( value != null )
				object.put(name, new JSONString(value) );
		}					
		
		public String getAttribute( String value ) {	
			String result = "";
			JSONValue jsonValue = object.get(value);
			if( jsonValue != null && jsonValue.isString() != null ){
				result = jsonValue.isString().stringValue();
			}
			return result;
		}

		public void setName( String name ){
			object = new JSONObject();
			documentObject.put( name, object );
			this.name = name;
		}
		
		public String getName() {
			return name;
		}			
	}
	

	private JSONObject documentObject;
	public JSONDocument(){		
	}
	
	public DocumentObject createObject(){
		documentObject = new JSONObject();
		return new JSONDocumentObject();
	}	
	
	public DocumentObject[] createCollection( String name, int size ){
		documentObject = new JSONObject();
		JSONArray array = new JSONArray();
		documentObject.put(name, array );
		DocumentObject[] objects = new DocumentObject[size];
		for( int i = 0; i<size; ++i ){
			objects[i] = new JSONDocumentObject();
		}
		return objects;
	}

	
	public String toString(){
		return documentObject.toString();
	}
	
	public void parse( String value ){
		documentObject = (JSONObject)JSONParser.parse(value);
	}
	
	public DocumentObject getObject() {
		String name = (String)documentObject.keySet().iterator().next();
		return new JSONDocumentObject( name, (JSONObject)documentObject.get(name) );
	}
	
	public DocumentObject[] getCollection() {
		String name = (String)documentObject.keySet().iterator().next();
		JSONArray array = (JSONArray)documentObject.get(name);
		DocumentObject[] objects = new DocumentObject[array.size()];
		for( int i = 0; i< array.size(); ++i ){
			JSONObject object = (JSONObject)array.get(i);
			objects[i] = new JSONDocumentObject( name, object );
		}
		return objects;
	}

	public String getFormatName() {
		return "json";
	}

}
